<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="模版名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入模版名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="处方类型" prop="prescriptionType">
        <el-select v-model="queryParams.prescriptionType" style="width: 200px;" placeholder="请选择处方类型" clearable>
          <el-option
            v-for="dict in doctor_drug_category"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker clearable
          v-model="queryParams.createTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择创建时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['ywx:template:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['ywx:template:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['ywx:template:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['ywx:template:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="templateList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="处方模版编号" align="center" prop="id" />
      <el-table-column label="模版名称" align="center" prop="name" />
      <el-table-column label="处方类型" align="center" prop="prescriptionType">
        <template #default="scope">
          <dict-tag :options="doctor_drug_category" :value="scope.row.prescriptionType"/>
        </template>
      </el-table-column>
      <el-table-column label="诊断" align="center" prop="diagnosisInfo">
        <template #default="scope">
          <dict-tag :options="doctor_diagnosis" :value="scope.row.diagnosisInfo ? scope.row.diagnosisInfo.split(',') : []"/>
        </template>
      </el-table-column>
      <el-table-column label="创建人员" align="center" prop="createPeople" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['ywx:template:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['ywx:template:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改西/成处方模版对话框 -->
    <el-dialog :title="title" v-model="open" width="1000px" append-to-body>
      <el-form ref="templateRef" :model="form" :rules="rules" label-width="80px">
        <div class="add_first">
          <el-form-item label="模版名称" prop="name" style="width: 300px;">
            <el-input v-model="form.name" placeholder="请输入模版名称" />
          </el-form-item>
          <el-form-item label="处方类型" prop="prescriptionType">
            <el-select v-model="form.prescriptionType" placeholder="请选择处方类型" style="width: 200px;">
              <el-option
                v-for="dict in doctor_drug_category"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </div>
        <el-form-item label="诊断" prop="diagnosisInfo">
          <el-checkbox-group v-model="form.diagnosisInfo">
            <el-checkbox
              v-for="dict in doctor_diagnosis"
              :key="dict.value"
              :label="dict.value">
              {{dict.label}}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="模版说明">
          <editor v-model="form.remark" :min-height="192"/>
        </el-form-item>
        <div class="add_first">
          <el-form-item label="创建人员" prop="createPeople">
            <el-input v-model="form.createPeople" placeholder="请输入创建人员" />
          </el-form-item>
          <!-- <el-form-item label="创建时间" prop="createTime">
            <el-input v-model="form.createTime" placeholder="请输入创建时间" />
          </el-form-item> -->
          <el-form-item label="创建时间" prop="createTime">
            <el-date-picker
            v-model="form.createTime"
            type="date"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请输入创建时间"
          />
          </el-form-item>
        </div>


        <div class="add_center">
          <h2>西/成处方模版内容</h2>
          <el-button type="success" @click="inner1">
            <el-icon class="el-icon--left"><Plus/></el-icon>
            添加药品
          </el-button>
        </div>
        <el-row :gutter="10">
          <el-col :span="4">
            <span>序号</span>
          </el-col>
          <el-col :span="4">
            <span>组号</span>
          </el-col>
          <el-col :span="4">
            <span>名称</span>
          </el-col>
          <el-col :span="4">
            <span>单次用量</span>
          </el-col>
          <el-col :span="4">
            <span>药品用法</span>
          </el-col>
          <el-col :span="4">
            <span>频度</span>
          </el-col>
        </el-row>
        <div v-for="item in drugList" :key="index">
        <el-row :gutter="10" v-if="ids1.includes(item.drugCode)">
          <el-col :span="4">
            <span>{{ item.id }}</span>
          </el-col>
          <el-col :span="4">
            <span>{{ item.drugCode }}</span>
          </el-col>
          <el-col :span="4">
            <span>{{ item.drugGenericName }}</span>
          </el-col>
          <el-col :span="4">
            <!-- <span>{{item.singleDose}}片</span> -->
            <el-input v-model="item.singleDose" style="width: 50px;"/>片
          </el-col>
          <el-col :span="4">
            <!-- <span>{{ item.drugUsage }}</span> -->
            
              <el-select v-model="item.drugUsage" placeholder="请选择药品用法">
                <el-option
                  v-for="dict in doctor_drug_usage"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            
          </el-col>
          <el-col :span="4">
            <!-- <span>{{ item.frequency }}</span> -->
              <el-select v-model="item.frequency" placeholder="请选择频度">
                <el-option label="一天1次" value='1' />
                <el-option label="一天2次" value='2' />
                <el-option label="一天3次" value='3' />
                <el-option label="一天4次" value='4' />
              </el-select>
          </el-col>
        </el-row>
      </div>
        <!-- <el-form-item label="处方模版药品" prop="drugId">
          <el-input v-model="form.drugId" placeholder="请输入处方模版药品" />
        </el-form-item> -->
        
      <div class="add_center">
        <h2>附加费用</h2>
        <el-button type="success" @click="inner2">
          <el-icon class="el-icon--left"><Plus /></el-icon>
          添加附加费
        </el-button>
      </div>
      <el-row :gutter="10">
        <el-col :span="6">
          <span>附加费用编号</span>
        </el-col>
        <el-col :span="6">
          <span>附加费用名称</span>
        </el-col>
        <el-col :span="6">
          <span>数量</span>
        </el-col>
        <el-col :span="6">
          <span>价格</span>
        </el-col>
      </el-row>
      <div v-for="item in costsList" :key="item.id">
        <el-row :gutter="10" v-if="ids2.includes(item.id)">
          <el-col :span="6">
            <span>{{ item.id }}</span>
          </el-col>
          <el-col :span="6">
            <span>{{ item.name }}</span>
          </el-col>
          <el-col :span="6">
            <!-- 显示并允许编辑附加费用数量 -->
            <el-input v-model="item.num" style="width: 50px;"/>
          </el-col>
          <el-col :span="6">
            <!-- 显示并允许编辑附加费用价格 -->
            <el-input v-model="item.price" style="width: 50px;" />
          </el-col>
        </el-row>
      </div>

      <!-- <el-form-item label="附加费用" prop="surchargeId">
          <el-input v-model="form.surchargeId" placeholder="请输入附加费用" />
        </el-form-item> -->
      </el-form>

      <el-dialog v-model="innerVisible1" width="1200px" title="选择药品" append-to-body >
        <el-table v-loading="loading" :data="drugList" @selection-change="handleSelectionChange1">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="id" />
      <el-table-column label="药品编码" align="center" prop="drugCode" />
      <el-table-column label="药品名称" align="center" prop="drugGenericName" />
      <el-table-column label="规格" align="center" prop="drugSpecification" />
      <el-table-column label="收费类别" align="center" prop="drugInformationId">
        <template #default="scope">
           {{informationList.find(item => item.id == scope.row.drugInformationId)?.drugInformationName || '未知' }}
        </template>
      </el-table-column>  
      <el-table-column label="采购价" align="center" prop="purchasePrice" />
      <el-table-column label="零售价" align="center" prop="retailPrice" />
      <el-table-column label="生产厂家" align="center" prop="drugManufacturer">
        <template #default="scope">
          <dict-tag :options="doctor_drug_manufacturer" :value="scope.row.drugManufacturer"/>
        </template>
      </el-table-column>
      <el-table-column label="药品状态" align="center" prop="drugStatus">
        <template #default="scope">
          <!-- <dict-tag :options="sys_common_status" :value="scope.row.drugStatus"/> -->
          <el-tag v-if="scope.row.drugStatus == '启用'" type="success">启用</el-tag>
          <el-tag v-if="scope.row.drugStatus == '停用'" type="danger">停用</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="creationTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.creationTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="250" >
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['drug:drug:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="blockUp(scope.row)" v-hasPermi="['drug:drug:edit']" v-if="scope.row.drugStatus == '启用'" >停用</el-button>
          <el-button link type="primary" icon="Delete" @click="blockUp(scope.row)" v-hasPermi="['drug:drug:edit']" v-if="scope.row.drugStatus == '停用'" >启用</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['drug:drug:remove']">删除</el-button>
        </template>
      </el-table-column> -->
    </el-table>
        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="submitForm1">确 定</el-button>
            <el-button @click="cancel1">取 消</el-button>
          </div>
        </template>
      </el-dialog>

       <!-- 选择附加费用对话框 -->
      <el-dialog v-model="innerVisible2" width="800px" title="附加费用" append-to-body>
        <el-table v-loading="loading" :data="costsList" @selection-change="handleSelectionChange2">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="附加费用编号" align="center" prop="id" />
        <el-table-column label="附加费用名称" align="center" prop="name" />
        <el-table-column label="数量" align="center" prop="num" />
        <el-table-column label="价格" align="center" prop="price" />
        <!-- <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['ywx:costs:edit']">修改</el-button>
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['ywx:costs:remove']">删除</el-button>
          </template>
        </el-table-column> -->
      </el-table>
        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="submitForm2">确 定</el-button>
            <el-button @click="cancel2">取 消</el-button>
          </div>
        </template>
      </el-dialog>


      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Template">
import { listTemplate, getTemplate, delTemplate, addTemplate, updateTemplate } from "@/api/ywx/template";
import { listDrug, getDrug, delDrug, addDrug, updateDrug,getDrugCode } from "@/api/drug/drug";
import { listCosts, getCosts, delCosts, addCosts, updateCosts } from "@/api/ywx/costs";
import { listInformation } from "@/api/drug/information";
import { onMounted } from "vue";

const { proxy } = getCurrentInstance();
const { doctor_drug_category, doctor_diagnosis } = proxy.useDict('doctor_drug_category', 'doctor_diagnosis');
const { doctor_packaging_unit, doctor_drug_manufacturer,  doctor_invoice_item, doctor_drug_usage } = proxy.useDict('doctor_packaging_unit', 'doctor_drug_manufacturer', 'doctor_drug_form', 'sys_common_status', 'sys_yes_no', 'doctor_drug_category', 'doctor_invoice_item', 'doctor_drug_usage');

const templateList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const ids1 = ref([]);
const ids2 = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const drugList = ref([]);
const innerVisible1 = ref(false);
const innerVisible2 = ref(false);
const costsList = ref([]);
const informationList = ref([]);


const data = reactive({
  form: {
    id: null,
    name: null,
    prescriptionType: null,
    diagnosisInfo: [],
    remark: null,
    createPeople: null,
    createTime: null,
    drugId: null,
    surchargeId: null
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    prescriptionType: null,
    createTime: null,
  },
  rules: {
    name: [
      { required: true, message: "模版名称不能为空", trigger: "blur" }
    ],
    diagnosisInfo: [
      { required: true, message: "诊断不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);


onMounted(() => {
  getList();
  getdrugList();
  getCostsList();
  getlistInformationList();
})
//附加费打开查询
function inner2() {
  innerVisible2.value = true;
}
/** 查询附加费用列表 */
function getCostsList() {
  loading.value = true;
  listCosts(queryParams.value).then(response => {
    costsList.value = response.rows;
    console.log(costsList.value);
    loading.value = false;
  });
}
function inner1() {
  innerVisible1.value = true;
}
/** 查询药品信息列表 */
function getdrugList() {
  loading.value = true;
  queryParams.value.params = {};
  listDrug(queryParams.value).then(response => {
    drugList.value = response.rows;
    console.log(drugList.value);
    // total.value = response.total;
    loading.value = false;
  });
}
/** 查询药品信息分类列表 */
function getlistInformationList() {
  loading.value = true;
  listInformation(queryParams.value).then(response => {
    informationList.value = response.rows;
    // console.log(informationList.value);
    loading.value = false;
  });
}

/** 查询西/成处方模版列表 */
function getList() {
  loading.value = true;
  listTemplate(queryParams.value).then(response => {
    templateList.value = response.rows;
    // console.log(response.rows);
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    prescriptionType: null,
    diagnosisInfo: [],
    remark: null,
    createPeople: null,
    createTime: null,
    drugId: null,
    surchargeId: null,
    del: null,
    ids1: [],
    ids2: []
  };
  proxy.resetForm("templateRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}
function handleSelectionChange1(selection) {
  ids1.value = selection.map(item => item.drugCode);
  // single.value = selection.length != 1;
  // multiple.value = !selection.length;
}
// 确定按钮
function submitForm1() {
  innerVisible1.value = false;
  console.log(ids1.value);
  // form.value.drugId = ids1.value;
  // console.log(form.value.drugId); 
}
// 取消按钮,清除选择框数据
function cancel1() {
  innerVisible1.value = false;
  ids1.value = []; 
}
function handleSelectionChange2(selection) {
  ids2.value = selection.map(item => item.id);
  // single.value = selection.length != 1;
  // multiple.value = !selection.length;
}
function submitForm2() {
  innerVisible2.value = false;
  console.log(ids2.value);
  // form.value.surchargeId = ids2.value;
  // console.log(form.value.surchargeId); 
}
function cancel2() {
  innerVisible2.value = false;
  ids2.value = []; 
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加西/成处方模版";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getTemplate(_id).then(response => {
    form.value = response.data;
    form.value.diagnosisInfo = form.value.diagnosisInfo.split(",");
    ids1.value = form.value.drugId.split(",");
    ids2.value = form.value.surchargeId.split(",");
    open.value = true;
    title.value = "修改西/成处方模版";
  });
}

/** 提交按钮 */
function submitForm() {
  form.value.drugId = ids1.value.join(",");
  form.value.surchargeId = ids2.value.join(",");
  console.log(form.value);
  proxy.$refs["templateRef"].validate(valid => {
    if (valid) {
      form.value.diagnosisInfo = form.value.diagnosisInfo.join(",");
      if (Array.isArray(form.value.createTime)) {
        form.value.createTime = form.value.createTime[0];
      }

      if (form.value.id != null) {
        updateTemplate(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          reset();
          getList();
        });
      } else {

        addTemplate(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          reset();
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除西/成处方模版编号为"' + _ids + '"的数据项？').then(function() {
    return delTemplate(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('ywx/template/export', {
    ...queryParams.value
  }, `template_${new Date().getTime()}.xlsx`)
}


</script>

<style>
.add_first{
  display: flex;
  justify-content: left;
}
.add_center{
  display: flex;
  justify-content: space-between;
}
</style>





